# -*- coding=utf-8 -*-
# 给定一个只包含 '(' 和 ')' 的字符串，找出最长的包含有效括号的子串的长度

# 示例 1:
# 输入: "(()"
# 输出: 2
# 解释: 最长有效括号子串为 "()"

# 示例 2:
# 输入: ")()())"
# 输出: 4
# 解释: 最长有效括号子串为 "()()"

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        heap = [];
        max_length = 0;
        for i in xrange(0, len(s)):
            print heap;
            if s[i] == "(":
                heap.append(s[i]);
                continue;
            if heap:
                length = 0;
                if type(heap[-1]) == type(0):
                    length += heap.pop();
                ### !!!!!!!汗，刚刚意识到heap中有的符号只会是"("
                if heap and heap[-1] == "(":
                    heap.pop();
                    length += 2;
                    if heap and type(heap[-1]) == type(0):
                        length += heap.pop();
                    heap.append(length);
                    max_length = length if length > max_length else max_length;
                    continue;

            heap = [];
        return max_length;

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype
        

t = Solution();
print t.longestValidParentheses("(())()(()((");
